import fetch from '@system.fetch'
import device from '@system.device'
import app from '@system.app'
import storage from '@system.storage'
import shortcut from '@system.shortcut'
import md5 from 'md5'
import network from '@system.network'
import prompt from '@system.prompt'
import router from '@system.router'

// sdk上报的地址
var report_sdk_url = 'https://applogs-qt.xayabx.com'
// sdk上报的密钥
var report_sdk_key = 'yunyousj@2021'
// sdk是否是本地环境
var report_sdk_is_test = process.env.NODE_ENV == 'development' ? true : false
// 服务端时间与客户端时间的差值
var timeDiff = 0
// sdk是否加载好了
var report_sdk_isReady = false
// 定时器自增id
var report_sdk_num = 1
// 定时器集合，用于初始化完成后清除
var report_sdk_timerArr = []
// 应用的包名
var report_sdk_pkg = ''
// 403十次不在重新请求
var report_flag = 0
// 上报所需的数据
var report_sdk_report_data = {
  event_id: '',
  event_name: '',
  scene: '',
  //
  lib_version: '1.1.4',
  //
  platform: 'Quickapp',
  //
  platform_code: 0,
  //
  os: 'android',
  //
  os_version: '',
  //
  app_version: '',
  //
  first_qid: '',
  //
  this_qid: '',
  //
  first_lid: '',
  //
  this_lid: '',
  //
  brand: 'other',
  //
  model: '',
  //
  ip: '',
  time_stamp: '',
  time_stamp_millis: '',
  //
  city: '',
  //
  province: '',
  //
  country: '',
  //
  device_id: '',
  //
  source_pkg: '',
  //
  newer_state: 0,
  //
  icon_state: 0,
  //
  menubar_state: 0,
  ad_style: '',
  ad_type: '',
  ext_field_1: '',
  ext_field_2: '',
  ext_field_3: '',
  ext_field_4: '',
  ext_field_5: '',
  ext_field_6: '',
  ext_field_7: '',
  ext_field_8: '',
  ext_field_9: '',
  ext_field_10: '',
  //
  screen_width: 0,
  //
  screen_height: 0,
  //
  network: 0,
  //
  login_state: 0,
  //
  pay_state: 0,
  //
  mode_state: '',
  page_url: '',
  ad_id: '',
  ad_network: 0,
  result: '',
  ad_position: '',
  referer: '',
  page_type: '',
  page_name: '',
  element_name: '',
  duration: 0,
  // 支付金额
  pay_amount: 0,
  // 会话id
  session_id: '',
  // 活动/广告id
  utm_ad_id: '',
  // 活动/广告名称
  utm_campaign: '',
  // 活动/广告内容
  utm_content: '',
  // 活动/广告媒介
  utm_medium: '',
  // 活动/广告来源
  utm_source: '',
  // 活动/广告关键字
  utm_term: '',
}
// 记录页面信息
var report_page_show_info = null

// 基础信息初始化
async function sdk_init(obj) {
  report_sdk_isReady = false
  // 获取应用信息
  let appInfo = app.getInfo()
  report_sdk_report_data.app_version = appInfo.versionName
    ? appInfo.versionName.replace(/\./g, '').toString()
    : ''
  report_sdk_report_data.source_pkg = appInfo.source.packageName
    ? appInfo.source.packageName
    : ''
  report_sdk_pkg = appInfo.packageName
  // 参数赋值
  if (obj && obj.utm_ad_id) {
    report_sdk_report_data.utm_ad_id = obj.utm_ad_id
  }
  if (obj && obj.utm_campaign) {
    report_sdk_report_data.utm_campaign = obj.utm_campaign
  }
  if (obj && obj.utm_content) {
    report_sdk_report_data.utm_content = obj.utm_content
  }
  if (obj && obj.utm_medium) {
    report_sdk_report_data.utm_medium = obj.utm_medium
  }
  if (obj && obj.utm_source) {
    report_sdk_report_data.utm_source = obj.utm_source
  }
  if (obj && obj.utm_term) {
    report_sdk_report_data.utm_term = obj.utm_term
  }
  // 获取手机信息
  if (report_sdk_report_data.platform_code == 0) {
    let deviceInfo = {
      data: '',
    }
    try {
      deviceInfo = await device.getInfo({})
    } catch (err) { }
    report_sdk_report_data.platform_code = deviceInfo.data.platformVersionCode
      ? Number(deviceInfo.data.platformVersionCode)
      : 0
    report_sdk_report_data.os = deviceInfo.data.osType
      ? deviceInfo.data.osType.toLowerCase()
      : ''
    report_sdk_report_data.os_version = deviceInfo.data.osVersionName
      ? deviceInfo.data.osVersionName
      : ''
    report_sdk_report_data.screen_width = deviceInfo.data.screenWidth
      ? ~~deviceInfo.data.screenWidth
      : 0
    report_sdk_report_data.screen_height = deviceInfo.data.screenHeight
      ? ~~deviceInfo.data.screenHeight
      : 0
    let tempBrand = deviceInfo.data.brand && deviceInfo.data.brand.toLowerCase()
    if (tempBrand == 'redmi' || tempBrand == 'xiaomi') {
      report_sdk_report_data.brand = 'xiaomi'
    } else {
      report_sdk_report_data.brand = 'other'
    }
    report_sdk_report_data.model = deviceInfo.data.model
      ? deviceInfo.data.model
      : ''
  }
  // 判断手机网络
  let networkType = {
    data: '',
  }
  try {
    networkType = await network.getType({})
  } catch (err) { }
  switch (networkType.data.type) {
    case '2g':
      report_sdk_report_data.network = 3
      break
    case '3g':
      report_sdk_report_data.network = 4
      break
    case '4g':
      report_sdk_report_data.network = 5
      break
    case 'wifi':
      report_sdk_report_data.network = 2
      break
    case 'none':
      report_sdk_report_data.network = 1
      break
    case '5g':
      report_sdk_report_data.network = 6
      break
    default:
      report_sdk_report_data.network = 0
      break
  }
  // 判断是否有胶囊
  report_sdk_report_data.menubar_state = obj.menubar_state ? 1 : 0
  // 判断用户登录状态
  report_sdk_report_data.login_state = obj && obj.login_state ? 1 : 0
  report_sdk_report_data.pay_state = obj && obj.pay_state ? 1 : 0
  report_sdk_report_data.mode_state = obj && obj.mode_state ? 1 : 0
  // 获取设备的安卓ID和用户ID
  if (!report_sdk_report_data.device_id) {
    let androidId = { data: '' }
    try {
      androidId = await device.getUserId({})
    } catch (err) { }
    if (androidId.data.userId) {
      report_sdk_report_data.device_id = androidId.data.userId
      storage.set({
        key: 'reportsdk_deviceid',
        value: report_sdk_report_data.device_id,
      })
    } else {
      let deviceId = { data: '' }
      try {
        deviceId = await storage.get({ key: 'reportsdk_deviceid' })
      } catch (err) { }
      if (deviceId.data) {
        report_sdk_report_data.device_id = deviceId.data
      } else {
        report_sdk_report_data.device_id =
          'SZ00' +
          Date.now() +
          parseInt(Math.random() * 899999999999 + 100000000000)
        storage.set({
          key: 'reportsdk_deviceid',
          value: report_sdk_report_data.device_id,
        })
      }
    }
  }
  // session_id赋值
  report_sdk_report_data.session_id =
    md5(report_sdk_report_data.device_id) + Date.now()
  // 获取缓存中的新用户标记
  if (report_sdk_report_data.newer_state == 0) {
    let isNewUser = {}
    try {
      isNewUser = await storage.get({ key: 'reportsdk_isNewUser' })
      isNewUser = isNewUser.data && JSON.parse(isNewUser.data)
    } catch (err) { }
    if (
      !isNewUser.createTime ||
      Date.now() - isNewUser.createTime > 10 * 1000 * 60 * 60 * 24
    ) {
      report_sdk_report_data.newer_state = 1
      let nowData = {
        status: 1,
        createTime: Date.now(),
      }
      storage.set({ key: 'reportsdk_isNewUser', value: nowData })
    } else {
      report_sdk_report_data.newer_state = 0
    }
  }
  // 如果传入了渠道ID和链接ID，则同步并判断今天第一次的渠道
  if (obj && obj.qd_id) {
    report_sdk_report_data.this_qid = obj.qd_id
  } else {
    report_sdk_report_data.this_qid = '-1'
  }
  if (obj && obj.link_id) {
    report_sdk_report_data.this_lid = obj.link_id
  } else {
    report_sdk_report_data.this_lid = '-1'
  }
  // 获取缓存中的渠道信息
  let today =
    new Date().getFullYear() +
    '/' +
    new Date().getMonth() +
    '/' +
    new Date().getDate()
  let storageQudao = { data: '' }
  try {
    storageQudao = await storage.get({ key: 'reportsdk_qudao' })
  } catch (err) { }
  if (storageQudao.data) {
    let storageData = JSON.parse(storageQudao.data)
    if (storageData.date == today) {
      report_sdk_report_data.first_qid = storageData.first_qid
      report_sdk_report_data.first_lid = storageData.first_lid
    } else {
      report_sdk_report_data.first_qid = report_sdk_report_data.this_qid
      report_sdk_report_data.first_lid = report_sdk_report_data.this_lid
      storage.set({
        key: 'reportsdk_qudao',
        value: {
          date: today,
          first_qid: report_sdk_report_data.this_qid,
          first_lid: report_sdk_report_data.this_lid,
        },
      })
    }
  } else {
    report_sdk_report_data.first_qid = report_sdk_report_data.this_qid
    report_sdk_report_data.first_lid = report_sdk_report_data.this_lid
    storage.set({
      key: 'reportsdk_qudao',
      value: {
        date: today,
        first_qid: report_sdk_report_data.this_qid,
        first_lid: report_sdk_report_data.this_lid,
      },
    })
  }
  // 获取桌面图标是否创建
  let desktop = { data: '' }
  try {
    desktop = await shortcut.hasInstalled({})
  } catch (err) { }
  report_sdk_report_data.icon_state = desktop.data ? 1 : 0
  // 从缓存中获取服务端与客户端的时间差
  let storageTimeDiff = { data: '' }
  try {
    storageTimeDiff = await storage.get({ key: 'reportsdk_time_diff' })
  } catch (err) { }
  if (storageTimeDiff.data) {
    timeDiff = ~~storageTimeDiff.data
  }
  // 接口请求ip和省市区
  if (!report_sdk_report_data.ip) {
    if (obj && obj.ip && obj.country && obj.province && obj.city) {
      report_sdk_report_data.ip = obj.ip
      report_sdk_report_data.country = obj.country
      report_sdk_report_data.province = obj.province
      report_sdk_report_data.city = obj.city
    } else {
      try {
        let xts = Math.round(new Date() / 1000) + timeDiff
        let ipDataJson = await fetch.fetch({
          url: 'https://ip.xayabx.com/',
          header: {
            Xts: xts,
            Xsign: md5('/yunyousj@2021' + xts),
          },
        })
        let ipData = JSON.parse(ipDataJson.data.data)
        report_sdk_report_data.ip = ipData.ip ? ipData.ip : ''
        report_sdk_report_data.country = ipData.country ? ipData.country : ''
        report_sdk_report_data.province = ipData.region ? ipData.region : ''
        report_sdk_report_data.city = ipData.city ? ipData.city : ''
      } catch (e) {
        LOG('REPORT', '----------------获取ip信息出错', e)
        report_sdk_report_data.ip = ''
        report_sdk_report_data.country = ''
        report_sdk_report_data.province = ''
        report_sdk_report_data.city = ''
      }
    }
  }
  report_sdk_isReady = true
}

// 上报事件
async function report(obj) {
  try {
    // 验证传入的参数是否正确
    if (typeof obj !== 'object') {
      console.error('SDK传入的参数不正确，必须是对象')
      return false
    }
    if (!obj.event_id) {
      console.error('SDK传入的参数event_id为必传')
      return false
    }
    if (!obj.event_name) {
      console.error('SDK传入的参数event_name为必传')
      return false
    }
    // 获取当前的时间戳，精确到豪秒
    let xtsMill = Date.now() + timeDiff * 1000
    // 计算当前的时间戳，精确到秒
    let xts = Math.floor(xtsMill / 1000)
    // 如果上报sdk还没初始化完毕，每隔1秒检测一次，初始化完成后再上报
    if (!report_sdk_isReady) {
      await new Promise((resolve, reject) => {
        report_sdk_num++
        let time = JSON.parse(JSON.stringify(report_sdk_num))
        let timer = setInterval(() => {
          try {
            if (report_sdk_isReady) {
              resolve(true)
              report_sdk_timerArr.forEach((element) => {
                if (element.time == time) {
                  element.timer && clearInterval(element.timer)
                }
              })
            }
          } catch (ee) {
            console.error('----------------上报SDK等待出错', ee)
            resolve(true)
          }
        }, 1000)
        report_sdk_timerArr.push({ timer: timer, time: time })
      })
    }
    let dataObj = JSON.parse(JSON.stringify(report_sdk_report_data))
    dataObj.time_stamp = xts
    dataObj.time_stamp_millis = xtsMill
    let dataObjVal = Object.assign(dataObj, obj)
    let canPostData = true
    if (report_sdk_is_test) {
      try {
        let checkResultJson = await fetch.fetch({
          url: 'https://data.xayabx.com/analysis/extranet/validate',
          data: dataObjVal,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'App-Origin': report_sdk_pkg,
          },
        })
        if (checkResultJson.data.code == 200) {
          let checkResult = JSON.parse(checkResultJson.data.data)
          if (checkResult.code == -1) {
            // prompt.showDialog({
            //   message: JSON.stringify(checkResult.data)
            // })
            canPostData = false
          }
        }
      } catch (e) {
        LOG('REPORT', '----------------数据校验出错', e)
      }
    }
    try {
      dataObjVal.pay_amount = parseFloat(dataObjVal.pay_amount.toFixed(2))
    } catch (e) {
      LOG('REPORT', '----------------转化金额出错', e)
    }
    if (canPostData) {
      LOG('REPORT', '----------------上报SDK上报的数据', dataObjVal)
      fetch
        .fetch({
          url: report_sdk_url + '/' + report_sdk_pkg,
          data: dataObjVal,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            Xts: xts,
            Xsign: md5('/' + report_sdk_pkg + report_sdk_key + xts),
          },
        })
        .then(async (res) => {
          if (res.data.code != 200) {
            console.error('----------------上报接口状态码出错', res.data.code)
          }
          if (res.data.code == 403 && report_flag < 10) {
            report_flag += 1
            try {
              let timeData = JSON.parse(res.data.data)
              if (timeData.STATUS == 2000) {
                timeDiff = timeData.DATA.Time - Math.round(new Date() / 1000)
                storage.set({ key: 'reportsdk_time_diff', value: timeDiff })
                report(obj)
              }
            } catch (e) {
              console.error('----------------本地时间校验出错', e)
            }
          }
        })
        .catch((error) => {
          console.error('----------------上报SDK返回逻辑执行出错', error)
        })
    }
  } catch (err) {
    console.error('----------------上报SDK执行出错', err)
  }
}

// 设置应用内特有属性
function set_attr(key, value) {
  if (report_sdk_report_data.hasOwnProperty(key)) {
    report_sdk_report_data[key] = value
  }
}

// 上报页面展示，记录时间
function page_show() {
  // 判断是否漏上报
  if (report_page_show_info && report_sdk_is_test) {
    prompt.showDialog({
      message: '上一个周期的onHide事件未埋点',
    })
  } else {
    // 记录当前页面信息
    let pageTime = Date.now()
    let pageUrl = ''
    try {
      let routerState = router.getState()
      pageUrl = routerState.path || '未知'
    } catch (t) {
      pageUrl = '未知'
    }
    report_page_show_info = {
      page_time: pageTime,
      page_url: pageUrl,
    }
  }
}

// 上报页面隐藏，计算时间间隔并上报
async function page_hide() {
  // 判断是否漏上报
  if (!report_page_show_info) {
    if (report_sdk_is_test) {
      prompt.showDialog({
        message: '上一个周期的onShow事件未埋点',
      })
    }
    return
  }
  // 获取当前的时间戳，精确到豪秒
  let dateNow = Date.now()
  // 计算所需的时间
  let xtsMill = dateNow + timeDiff * 1000
  let xts = Math.floor(xtsMill / 1000)
  let duration = dateNow - report_page_show_info.page_time
  let page_url = report_page_show_info.page_url
  report_page_show_info = null
  // 如果上报sdk还没初始化完毕，每隔1秒检测一次，初始化完成后再上报
  if (!report_sdk_isReady) {
    await new Promise((resolve, reject) => {
      report_sdk_num++
      let time = JSON.parse(JSON.stringify(report_sdk_num))
      let timer = setInterval(() => {
        try {
          if (report_sdk_isReady) {
            resolve(true)
            report_sdk_timerArr.forEach((element) => {
              if (element.time == time) {
                element.timer && clearInterval(element.timer)
              }
            })
          }
        } catch (ee) {
          console.error('----------------上报SDK等待出错', ee)
          resolve(true)
        }
      }, 1000)
      report_sdk_timerArr.push({ timer: timer, time: time })
    })
  }
  // 组合需要上报的数据
  let dataObj = JSON.parse(JSON.stringify(report_sdk_report_data))
  let obj = {
    event_id: 'used_duration',
    event_name: '用户使用时长',
    time_stamp: xts,
    time_stamp_millis: xtsMill,
    duration: duration,
    page_url: page_url,
  }
  let dataObjVal = Object.assign(dataObj, obj)
  LOG('REPORT', '----------------上报SDK用户上报的数据', dataObjVal)
  // 上报页面访问时长
  fetch
    .fetch({
      url: report_sdk_url + '/' + report_sdk_pkg,
      data: dataObjVal,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        Xts: xts,
        Xsign: md5('/' + report_sdk_pkg + report_sdk_key + xts),
      },
    })
    .then(async (res) => {
      if (res.data.code != 200) {
        console.error('----------------上报接口状态码出错', res.data.code)
      }
      if (res.data.code == 403 && report_flag < 10) {
        report_flag += 1
        try {
          let timeData = JSON.parse(res.data.data)
          if (timeData.STATUS == 2000) {
            timeDiff = timeData.DATA.Time - Math.round(new Date() / 1000)
            storage.set({ key: 'reportsdk_time_diff', value: timeDiff })
            report(obj)
          }
        } catch (e) {
          console.error('----------------本地时间校验出错', e)
        }
      }
    })
    .catch((error) => {
      console.error('----------------上报SDK返回逻辑执行出错', error)
    })
}

const reportsdk = {
  sdk_init: sdk_init,
  report: report,
  set_attr: set_attr,
  page_show: page_show,
  page_hide: page_hide,
}
const hooktoglobal = global.__proto__ || global
hooktoglobal.REPORT_SDK = reportsdk
export default reportsdk
